package com.wangxiaonan.coupon.componet;

import com.wangxiaonan.coupon.common.Constant;
import com.wangxiaonan.coupon.config.RedisManeger;
import com.wangxiaonan.coupon.domain.CouponInfo;
import com.wangxiaonan.coupon.repository.CouponInfoDao;
import com.wangxiaonan.coupon.service.CouponInfoService;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: wangxiaonan
 * @Date: 2019/1/11
 **/
@Component
@Service
public class TaskInit {

    private static final Logger logger = LoggerFactory.getLogger(TaskInit.class);
    @Resource
    private CouponInfoDao couponInfoDao;

    @Resource
    private CouponInfoService couponInfoService;

    @Scheduled(cron = "0/30 * * * * ?")
    @Transactional
    public void syncCirculation() {
        logger.info("[TaskInit.syncCirculation] ============== task ===============");
        CouponInfo info = new CouponInfo();
        info.setStatus(1);
        Example<CouponInfo> example = Example.of(info);
        List<CouponInfo> list = couponInfoDao.findAll(example);
        for (CouponInfo coupon : list) {
            if (new Date().before(coupon.getExpireDate())) {
                logger.info("[TaskInit.syncCirculation] coupon:{}", coupon.getId());
                String token = RedisManeger.lock(Constant.COUPON_CIRCULATION_LOCK_KEY + coupon.getId(), 3000, 600000);
                if (StringUtils.isNotBlank(token)) {
                    try {
                        coupon.setCirculation(
                                Integer.valueOf(RedisManeger.get(Constant.COUPON_CIRCULATION_PREFIX + coupon.getId())));
                    } finally {
                        RedisManeger.releaseLock(Constant.COUPON_CIRCULATION_LOCK_KEY + coupon.getId(), token);
                    }
                }
            }
        }
    }
}
